package flante;

import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * <p>Title: Flante MainActivity</p>
 * <p>Description: This class is invoked on startup.</p>
 * @author Aaron Cook, Mike Haas, Kyle Kolstad
 * @email aaron.cook@my.uwrf.edu, michael.haas.@my.uwrf.edu, kyle.kolstad@my.uwrf.edu
 * @date 12/4/2013
 */
public class MainActivity extends Activity implements OnClickListener {
    /**
     * MainActivity class data members
     */
    TextView textViewIsConnected;
    EditText Description;
    Button buttonPost;
    Button buttonListEvents;
    Event event;


    /**
     * Creates activity and initializes data members
     * gets reference to the views
     * check if you are connected or not
     * add click listener to Button "POST"
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewIsConnected = (TextView) findViewById(R.id.textViewIsConnected);
        Description = (EditText) findViewById(R.id.Description);
        buttonPost = (Button) findViewById(R.id.buttonPost);
        buttonListEvents = (Button) findViewById(R.id.buttonListEvents);

        if(isConnected()){
            textViewIsConnected.setBackgroundColor(0xFF00CC00);
            textViewIsConnected.setText("You are connected");
        }
        else{
            textViewIsConnected.setText("You are NOT connected");
        }

        buttonPost.setOnClickListener(this);
        buttonListEvents.setOnClickListener(this);
    }

    /**
     * creates HttpClient, and makes a POST request to the given URL. Then builds a jsonObject and
     * converts the JSONObject to JSON toString. Set json to StringEntity, sets httpPost Entity,
     * Sets some headers to inform server about the type of the content Execute POST request to the given URL.
     * receives response as inputStream and converts inputStream to a string.
     * @param url
     * @param event
     * @return String result
     * @see org.apache.http.client.methods.HttpPost
     * @see org.apache.http.impl.client.DefaultHttpClient
     * @see org.apache.http.entity.StringEntity
     * @see org.apache.http.HttpResponse
     * @see org.apache.http.client.HttpClient
     * @see org.json.JSONObject
     */
    public static String POST(String url, Event event){
        InputStream inputStream;
        String result = "";
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            String json = "";

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("description", event.getDescription());
            json = jsonObject.toString();

             StringEntity stringEntity = new StringEntity(json);

            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();


            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
            return result;
    }

    /**
     *Indicates whether network connectivity exists
     * and it is possible to establish connections and pass data.
     * @return boolean
     * @see  android.net.NetworkInfo#isConnected()
     */
    public boolean isConnected(){
        ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

    /**
     * Event Handler if case R.id.buttonPost it will call AsynTask to perform network operation on separate thread
     * if case R.id.buttonListEvents it will start the EventListActivity
     * @param view
      * @see android.view.View.OnClickListener#onClick(android.view.View)
     *  @see android.content.Intent#Intent(android.content.Context, Class)
     */
    public void onClick(View view) {

        switch(view.getId()){
            case R.id.buttonPost:
                if(!validate())
                    Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
                      new HttpAsyncTask().execute("http://10.0.2.2:9000/events");
                break;
            case R.id.buttonListEvents:
                Intent intent = new Intent(this, EventListActivity.class);
                startActivity(intent);
                break;
        }

    }
    /**
     * <p>Title: HttpAsyncTask Thread</p>
     * <p>Description:Creates a thread that runs in the background.</p>
     * @author Aaron Cook, Mike Haas, Kyle Kolstad
     * @email aaron.cook@my.uwrf.edu, michael.haas.@my.uwrf.edu, kyle.kolstad@my.uwrf.edu
     * @date 12/4/2013
     */
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {


        /**
         * creates a new event object with the user input and calls the
         * POST(urls[0],event) method
         *@see android.os.AsyncTask#doInBackground(Object[])
         *
         */
        @Override
        protected String doInBackground(String... urls) {

            event = new Event();
            event.setDescription(Description.getText().toString());


            return POST(urls[0],event);
        }

        /**
         *Runs on the UI thread after doInBackground(Params...).
         * Makes a toast message that tells you the "Data Sent!"
         * @param result
         * @see android.os.AsyncTask#onPostExecute(Object)
         */

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Validates the specified input.
     * @return boolean
     * @see javax.xml.validation.Validator#validate(javax.xml.transform.Source)
     */
    private boolean validate(){
        if(Description.getText().toString().trim().equals(""))
            return false;
        else
            return true;
    }

    /**
     *Converts the inputSteam into a String result
     * @param inputStream
     * @return result
     * @throws IOException
     * @see java.io.InputStreamReader
     * @see java.io.BufferedReader
     */
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
}
